package com.example.hcd.functionactivity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.hcd.R;
import com.example.hcd.adapt.NoticeListAdapt;
import com.example.hcd.datamanage.NoticeData;
import com.example.hcd.internet.InternetKeep;
import com.example.hcd.internet.LinkHelp;
import com.example.hcd.internet.URLS;
import com.example.hcd.tool.ImageBtnMove;
import com.example.hcd.tool.MyLoadingDialog;
import com.example.hcd.tool.OnDoubleClickListener;
import com.example.hcd.tool.ToastHelp;
import com.example.hcd.tool.XListView;
import com.example.hcd.tool.XListView.IXListViewListener;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class NoticeListActivity extends BaseActivity implements OnDoubleClickListener,OnClickListener,OnItemClickListener,OnItemLongClickListener,IXListViewListener{

	private Context context;
	private LayoutInflater inflater;
	private View main_view;
	//all my notRead
	private String type;
	private TextView title_content;
	private XListView list;
	private int currentPage = 1;
	private NoticeListAdapt adapt;
	public static Handler mHandler;
	private boolean shouldRefresh = false;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		mPageName = "NoticeListActivity";
		// 初始化
		context = this;
		inflater = LayoutInflater.from(this);
		main_view = inflater.inflate(R.layout.my_task_list_view, null);
		setContentView(main_view);
		type = getIntent().getStringExtra("TYPE_NOTICE");
		title_content = (TextView) findViewById(R.id.title_content);
		list = (XListView) findViewById(R.id.lists);
		list.setPullLoadEnable(true);
		list.setXListViewListener(this);
		list.setOnItemClickListener(this);
		list.setOnItemLongClickListener(this);
		//
		// 返回键
		ImageView backBtn = (ImageView) findViewById(R.id.title_bar_btn_left);
		// 刷新
		ImageView refreshBtn = (ImageView) findViewById(R.id.title_bar_btn_right);
		backBtn.setOnClickListener(this);
		refreshBtn.setOnClickListener(this);
		
		initList();
		
		mHandler = new Handler(){  
	        public void handleMessage(Message msg) { 
	        	final int NOW_ID = msg.arg2;
	        	//刷新公告
	        	NoticeListActivity.this.runOnUiThread(new Runnable(){
					@Override
					public void run() {
						DeleteTask dele = new DeleteTask(context,NOW_ID);
						dele.execute();
						
					}
					});
	        };  
	    };
	}

	private void initList()
	{
		if(type.equals("all"))
		{
			title_content.setText("公告管理");
		}else if(type.equals("my"))
		{
			title_content.setText("我的公告");
			
		}if(type.equals("notRead"))
		{
			title_content.setText("未读公告");
			shouldRefresh = true;
		}
		
		LoadTaskInfoList list = new LoadTaskInfoList(context,1);
		list.execute();
		if(type.equals("all"))
		{
			RelativeLayout scroll = (RelativeLayout)main_view.findViewById(R.id.scorllView);
			ImageBtnMove btn = new ImageBtnMove(this);
			btn.setActivity(this);
			btn.setListen(this);
			btn.setBackgroundDrawable(getResources().getDrawable(R.drawable.add));
			RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(100, 100);
	        layoutParams.topMargin=200;
	        layoutParams.leftMargin=8;
	        layoutParams.rightMargin=8;
	        layoutParams.bottomMargin=8;
			scroll.addView(btn,layoutParams);
		}
		
		
	}
	

	private class LoadTaskInfoList extends AsyncTask<String, Integer, String> {

		private Context context;
		private int index;
		private MyLoadingDialog dialog;
		
		public LoadTaskInfoList(Context context, int index) {
			this.context = context;
			this.index = index;
		}

		@Override
		protected void onPreExecute() {
			dialog = new MyLoadingDialog(context, null, "加载中...", false);
			dialog.setPullToRefreshListView(list);
		}

		@Override
		protected String doInBackground(String... params) {
			String result = null;
			HttpResponse response = null;
			BufferedReader reader = null;
			try {
				ArrayList<NameValuePair> vs = new ArrayList<NameValuePair>();
				//vs.add(new BasicNameValuePair("taskId", taskId));
				vs.add(new BasicNameValuePair("currentPage", ""+currentPage));
				vs.add(new BasicNameValuePair("type", type));
				response = LinkHelp.post(URLS.getNoticeList(), vs, false);
				//System.out.println(URLS.getTaskInfoByType(type));
				if (response != null) {
					StatusLine line = response.getStatusLine();
					if (line.getStatusCode() == 200) {
						reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
						StringBuilder sb = new StringBuilder();
						for (String s = reader.readLine(); s != null; s = reader.readLine()) {
							sb.append(s);
						}
						result = sb.toString();
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (reader != null) {
					try {
						reader.close();
						
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			dialog.dimiss();
			if(dialog.mCancel)
			{
				return;
			}
			
			if (!TextUtils.isEmpty(result)) {

				if (result.contains("error")) 
				{
					onLoad();
					try {
						JSONObject obj = new JSONObject(result);
						String msg = obj.getString("msg");
						ToastHelp.doToast(NoticeListActivity.this, msg);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} else {

					if(index >1)
					{
						
						InternetKeep.getInstence().parseNoticeList(result);
						refreshNoticeList();
						onLoad();
						
					}else
					{
						InternetKeep.getInstence().getNoticeList().clear();
						InternetKeep.getInstence().parseNoticeList(result);
						initNoticeList();
						
						onLoad();
						
					}
	
					if(InternetKeep.getInstence().isHaveNextPage)
					{
						list.removeFooterViews();
					}
				}

			}else
			{
					ToastHelp.doToast(NoticeListActivity.this, "网络异常！");
			}
		}

	}
	
	private class DeleteTask extends AsyncTask<String, Integer, String> {

		private Context context;
		private MyLoadingDialog dialog;
		private int id;
		
		public DeleteTask(Context context,int id) {
			this.context = context;
			this.id = id;
		}

		@Override
		protected void onPreExecute() {
			dialog = new MyLoadingDialog(context, null, "加载中...", false);
			dialog.setPullToRefreshListView(list);
		}

		@Override
		protected String doInBackground(String... params) {
			String result = null;
			HttpResponse response = null;
			BufferedReader reader = null;
			try {
				ArrayList<NameValuePair> vs = new ArrayList<NameValuePair>();
				
				String ids = InternetKeep.getInstence().getNoticeList().get(id).getId();
				
				vs.add(new BasicNameValuePair("id", ids));
				response = LinkHelp.post(URLS.getDeleteNotice(), vs, false);
				//System.out.println(URLS.getTaskInfoByType(type));
				if (response != null) {
					StatusLine line = response.getStatusLine();
					if (line.getStatusCode() == 200) {
						reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
						StringBuilder sb = new StringBuilder();
						for (String s = reader.readLine(); s != null; s = reader.readLine()) {
							sb.append(s);
						}
						result = sb.toString();
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (reader != null) {
					try {
						reader.close();
						
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			dialog.dimiss();
			if(dialog.mCancel)
			{
				return;
			}
			
			if (!TextUtils.isEmpty(result)) {

				if (result.contains("error")) 
				{
					try {
						JSONObject obj = new JSONObject(result);
						String msg = obj.getString("msg");
						ToastHelp.doToastInTop(context, msg);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					
				} else if( result.contains("success"))
				{
					onRefresh();
					Toast.makeText(context, "删除成功",Toast.LENGTH_SHORT).show();
				}

			}else
			{
				list.stopRefresh();
				list.stopLoadMore();
				ToastHelp.doToastInTop(context, "网络异常");
			}
		}

	}
	public void refreshNoticeList()
	{
		ArrayList<NoticeData> data = InternetKeep.getInstence().getNoticeListCatch();

		adapt.addList(data);
	}
	public void initNoticeList()
	{
		adapt = new NoticeListAdapt(context);
		if(type.equals("all"))
		{
			adapt.ishaveXugai(true);
		}
		ArrayList<NoticeData> data = InternetKeep.getInstence().getNoticeList();
		
		adapt.setList(data);
		list.setAdapter(adapt);
		
		if(data.size()==0)
		{
			list.removeFooterViews();
		}
	}
	
	
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		int id = arg0.getId();
		switch (id) {
		case R.id.title_bar_btn_left:
			finish();
			break;
			
		case R.id.title_bar_btn_right:
			new LoadTaskInfoList(context, currentPage=1).execute();
			break;

		default:
			break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		System.out.println("详情"+arg2);
		Intent intent = new Intent(context, NoticeDetailActivity.class);
		intent.putExtra("NOTICE_NUM", ""+arg2);
		intent.putExtra("should_refresh", shouldRefresh);
		startActivityForResult(intent, 5);
		
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		System.out.println("刪除"+arg2);
		return true;
	}

	@Override
	public void OnSingleClick(View v) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void OnDoubleClick(View v) {
		// TODO Auto-generated method stub
		Intent intent = new Intent(NoticeListActivity.this,NoticeNewCreate.class);
		startActivity(intent);
	}
	
	@Override
	public void onRefresh() {
		list.addFooterViews();
		new LoadTaskInfoList(context, currentPage=1).execute();
				
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		if(!InternetKeep.getInstence().isHaveNextPage)
		{
			currentPage++;
			new LoadTaskInfoList(context, currentPage).execute();
		}else
		{
			Toast.makeText(context, "已经到最后", Toast.LENGTH_SHORT).show();
			onLoad();
		}
	}
	
	private void onLoad() {
		SimpleDateFormat format = new SimpleDateFormat(
				"yyyy年MM月dd日  HH:mm");
		String date = format.format(new Date());
		list.stopRefresh();
		list.stopLoadMore();
		list.setRefreshTime(date);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode == Activity.RESULT_OK)
		{
			
				if(requestCode == 5)
				{
					onRefresh();
				}
			
		}
		
	}
	

}
